#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
using namespace std;

void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << "local_ip,local_port\n" << endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(3);
    }
    string sercerip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        cout << "创建网路套接字失败" << endl;
    }

    string message;

    //构建目标主机的socket信息
    sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(sercerip.c_str());

    while(true)
    {
        cout << "输入要发送的消息" << endl;
        getline(cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(sockaddr*)&server,sizeof(server));

        char buffer[1024];
        sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);

        if(n > 0)
        {
            buffer[n] = 0;
            cout << "server echo#: " << buffer << endl;
        }
    }

    return 0;
}


